<template>
	<view class="">
		<!-- 招标信息 -->
		<view class="active-list">
			<view class="active-title">
				<view class="active-top">
					采购产品<text class="">*</text><text v-if="blurProNullShow">请输入采购产品</text>
				</view>
				<u--textarea placeholder="请填写采购产品名称" @blur="proBlur(productName)" v-model="productName" border="none"
					maxlength="12" count="true"></u--textarea>
			</view>
			<view class="active-title">
				<view class="active-top">
					采购数量<text class="">*</text><text v-if="blurProNumNullShow">请输入以数字开头的数量</text>
				</view>
				<u--textarea :formatter="numFormatter" ref="textarea" placeholder="请填写采购产品数量" @blur="proNumBlur(productNum)" v-model="productNum" border="none"
					maxlength="10" count="true"></u--textarea>
			</view>
			<view class="active-title">
				<view class="active-top">
					采购期限<text class="">*</text>
				</view>
				<u-radio-group v-model="buyRadiovalue" class="buy-radio" placement="row" @change="groupChange"
					iconSize="32" size="32">
					<u-radio :customStyle="index==0?customStyle0:customStyle1" iconSize="32" labelSize="32"
						v-for="(item, index) in buyRadiolist" :key="index" :label="item.name" :name="item.name">
					</u-radio>
				</u-radio-group>
				<view class="buy-many" v-if="buyManyShow">
					*选择长期采购后,每10天您的采购需求单将被重新发布曝光
				</view>
			</view>


			<view class="active-title active-time" v-show="buyOneShow">
				<view class="active-top">
					截止日期<text class="">*</text>
				</view>
				<!-- <text @click="startClick" class="start-time">{{startTime}}</text> -->
				<u--textarea placeholder="有效期不超过一个月" @focus="startClick" v-model="startTime" border="none">
				</u--textarea>
			</view>
			<view class="active-title describe-title">
				<view class="active-top">
					产品描述<text class=""></text>
				</view>
				<u--textarea placeholder="完善采购信息,帮助供应商了解你的采购需求"  v-model="productDescribe" border="none"
					maxlength="200" count="true"></u--textarea>
			</view>

			<view class="active-title active-info">
				<view class="active-top">
					图片<text class=""></text>
				</view>
				<view class="active-img-des">
					请上传采购产品相关图片，如产品细节图、采购清单等
				</view>
				<view class="active-info-img">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="4" width="140" height="140">
					</u-upload>
				</view>
			</view>

			<view class="sign-up">
				<u-button type="primary" shape="circle" color="#2684ff" text="填写完成" @click="submitActive(item,index)">
				</u-button>
			</view>

		</view>

		<u-calendar :show="timeShow" :maxDate="maxDate" @confirm="dateConfirm" @close="dateClose"
			closeOnClickOverlay="true"></u-calendar>
	</view>
</template>

<script>
	const d = new Date()
	const year = d.getFullYear()
	let month = d.getMonth() + 1
	month = month < 10 ? `0${month}` : month
	const date = d.getDate()
	import baseConfig from '@/config/baseUrl.js'
	import {
		mapState,
		mapGetters
	} from 'vuex'
	export default {

		data() {
			return {

				blurProNullShow: false, //采购产品输入信息为空失焦显示
				productName: '', //采购产品输入信息
				blurProNumNullShow: false, //采购产品数量输入信息为空失焦显示
				productNum: '', //采购产品数量输入信息

				// 基本案列数据
				buyRadiolist: [{
						name: '单次采购',
						id:1,
						disabled: false
					},
					{
						name: '长期采购',
						id:0,
						disabled: false
					}
				],
				//单次采购或者长期采购的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				buyRadiovalue: '',
				buyOneShow: false, //单次采购截止日期显示
				buyManyShow: false, //长期采购显示
				maxDate: `${year}-${month}-${date + 31}`,
				customStyle0: {
					marginBottom: '8px',
					fontSize: '32px',
					marginLeft: '0'
				},
				customStyle1: {
					marginBottom: '8px',
					fontSize: '32px',
					marginLeft: '15px'
				},
				productDescribe:'',

				imageUrl: '', //图篇
				imgArr:[],
				fileList1: [],
				// 开始时间事件显示隐藏
				timeShow: false,
				status:"-1",//状态0:长期  1:单次
				startTime:'',//单次采购的截止时间
				historyInfo:null,
				editId:''
			}
		},
		onReady() {
			// 如果需要兼容微信小程序的话，需要用此写法
			// this.$refs.textarea.setFormatter(this.numFormatter)
		},
		onLoad(option) {
			if(option.editId){
				this.editId=option.editId
				this.queryEditInfo()
			}
			this.userInfo = uni.getStorageSync('_userInfo')
			console.log(this.userInfo)

			// this.historyInfo = this.$store.state.myBuyInfo
			// console.log(this.historyInfo)
			// if(this.historyInfo){
			// 	uni.setStorageSync(`supplyJumpTo`,4)
			// 	uni.setStorageSync(`historyJumpTo`,1)
			// 	this.productName=this.historyInfo.name

			// 	this.productNum=this.historyInfo.buyNum

			// 	this.status=this.historyInfo.status
			// 	if(this.status==0){
			// 		this.buyRadiovalue='单次采购'
			// 	}else{
			// 		this.buyRadiovalue='长期采购'
			// 	}
			// 	this.startTime=this.historyInfo.startTime
			// 	this.productDescribe=this.historyInfo.perfile
			// 	// this.imgArr=this.historyInfo.image.split('"')
			// 	let imgLists=this.parseString(this.historyInfo.fileList)
			// 	console.log(this.fileList1)
			// 	if(imgLists.length!=0){
			// 		this.fileList1=[]
			// 		imgLists.forEach(item=>{
			// 			let date={
			// 				message: "",
			// 				size: 2351629,
			// 				status: "success",
			// 				thumb: item,
			// 				type: "image",
			// 				url: item
			// 			}
			// 			this.fileList1.push(date)
			// 		})
			// 	}else{
			// 		this.fileList1=[]
			// 	}
			// }else{
			// 	uni.setStorageSync(`supplyJumpTo`,44)
			// }
		},
		onShow() {


		},
		methods: {

			queryEditInfo(){
				this.$api.queryMyCouponListsById(this.editId).then(res=>{
					console.log(res)
					if(res.success){
						this.$store.commit('setMyBuyInfo', res.result)
						// this.$api.queryMyCouponLists(this.name,this.openId,this.pageNo,this.pageSize).then(res => {
							console.log(res)

							if (res.success) {
								this.productName=res.result.name

								this.productNum=res.result.buyNum

								this.status=res.result.status
								if(this.status=='1'){
									this.buyRadiovalue='单次采购'
									this.groupChange('单次采购')
									this.startTime=res.result.endTime
								}else{
									this.buyRadiovalue='长期采购'
									this.groupChange('长期采购')
								}
								// this.startTime=res.result.startTime
								this.productDescribe=res.result.perfile
								let imgLists=[]
								this.fileList1=[]
								imgLists=res.result.fileList.split(',')
								// let imgLists=this.parseString(res.result.fileList)
								console.log(imgLists)
								console.log(this.fileList1)
								if(imgLists.length!=0){
									this.fileList1=[]
									imgLists.forEach(item=>{
										let date={
											message: "",
											size: 2351629,
											status: "success",
											thumb: item,
											type: "image",
											url: item
										}
										this.fileList1.push(date)
									})
								}else{
									this.fileList1=[]
								}
							}
						// })

					}
				})
			},
			// 数量输入框限制输入字数
			numFormatter(value){
				console.log(value)
				// 让输入框只能输入数值，过滤其他字符
				return value.replace(/[^0-9]/ig, "")
			},
			parseString(str){
			  // 一个 flag 标识当前的对应结束点
			  let right = null;
			  let parent = null;

			  let key = '';
			  let value = '';

			  for(let i = 0; i < str.length; i++){
			    const letter = str[i];

			    if(letter === '['){
			      // 这里是一个“高街元素”，做好笔记！
			      // 小老虎这里巧妙地将相对应右括号记录下来，
			      // 这样在下面判断结束的时候就会变得相当便捷。
			      right = ']';
			      parent = new Array();
			    }else if(letter === ']'){
			      if(right === letter && value){
			        parent.push(value);
			        value = '';
			        right = null;
			      }
			    }else if(letter === ','){
			      if(right === ']'){
			        parent.push(value);
			        value = '';
			      }
			    }else{
			      // non empty
			      if(letter && letter !== ' '){
			        value += letter;
			      }
			    }
			  }
			  return parent;
			},
			// 采购产品失焦
			proBlur(e) {
				console.log(e)
				if (e) {
					this.blurProNullShow = false
				} else {
					this.blurProNullShow = true
				}
			},
			// 采购产品数量失焦
			proNumBlur(e) {
				console.log(e)
				if (e) {
					this.blurProNumNullShow = false
				} else {
					this.blurProNumNullShow = true
				}
			},
			// 单次采购和长期采购选择切换
			groupChange(n) {
				console.log('groupChange', n);
				this.buyRadiovalue=n
				if (this.buyRadiovalue == "单次采购") {
					this.buyOneShow = true
					this.buyManyShow = false
					this.status=1
					this.startTime=''
				} else {
					this.buyOneShow = false
					this.buyManyShow = true
					this.status=0
				}
			},
			// 日期选择确认
			dateConfirm(e) {
				console.log(e)
				this.startTime = e[0]
				this.timeShow = false
				console.log(this.startTime)
			},
			// 日期选择关闭
			dateClose() {
				this.timeShow = false
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log(event.file[0])
				// this.imageUrl = event.file[0].url
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						// status: 'uploading',
						// message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				console.log(url)
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							let data = JSON.parse(res.data)
							console.log("测试一下上传视频")
							if (data.success) {
								this.imageUrl = data.message
								// this.videoUrl=data.message
								resolve(data.message)
							}
						}
					});
				})
			},
			// 截止时间选择
			startClick() {
				this.timeShow = true
			},

			// 提交活动
			submitActive(item, index) {
				console.log(this.fileList1)
				this.fileList1.forEach(item=>{
					this.imgArr.push(item.url)
				})
				if (this.productName == "") {
					uni.showToast({
						title: "采购产品名称不能为空",
						icon: 'none'
					});
					return false
				}
				if (this.productNum == "") {
					uni.showToast({
						title: "采购产品数量不能为空",
						icon: 'none'
					});
					return false
				}
				if(this.status=='-1'){
					uni.showToast({
						title: "请选择采购期限",
						icon: 'none'
					});
					return false
				}
				if(this.status=="1"){
					if (this.startTime == "") {
						uni.showToast({
							title: "截止时间不能为空",
							icon: 'none'
						});
						return false
					}
				}


				// let openId = uni.getStorageSync('openId')
				// console.log("这是openId", openId)
				// let cardId = uni.getStorageSync('cardId')
				// console.log("这是cardId", cardId)
				let data = {
					name: this.productName,
					buyNum: this.productNum,
					startTime: this.startTime,
					status:this.status,
					image: this.imgArr.toString(),
					perfile:this.productDescribe,
				}
				this.$store.commit('setBuyInfo', data)
				uni.navigateTo({
					url: '/pagesBusiness/purchaseSubmit/purchaseSubmit'
				})

				// this.$api.releaseActive(data).then(res => {
				// 	console.log(res)
				// 	// this.signSuccess=res.result
				// 	if (res.success) {
				// 		uni.showToast({
				// 			title: res.message,
				// 			icon: 'none'
				// 		});
				// 		setTimeout(() => {
				// 			uni.navigateTo({
				// 				url: '/pagesBusiness/purchaseSubmit/purchaseSubmit'
				// 			})
				// 		}, 1000)

				// 	} else {
				// 		uni.showToast({
				// 			title: res.message,
				// 			icon: 'none'
				// 		});
				// 	}
				// })
			}
		}
	}
</script>

<style lang="scss" scoped>
	.active-list {
		background: #FFFFFF;
		border-bottom: 1upx solid #f6f6f6;
		padding: 41upx 30upx 100upx;
		position: relative;

		.active-title {
			letter-spacing: 3upx;
			font-size: 30upx;
			font-family: PingFang SC;
			font-weight: 400;
			color: #666666;
			// height: 110upx;
			border-bottom: 1px solid #f6f6f6;
			margin-top: 20upx;

			.active-top {
				font-size: 26upx;
				font-weight: bold;

				text {
					color: red;
					margin-left: 5upx;
				}
			}
			.buy-radio{

			}
			.buy-many {
				font-size: 22upx;
				color: #2979ff;
				padding-bottom: 10upx;
			}

			::v-deep .u-radio-group {
				margin-top: 20upx;
				margin-bottom: 20upx;
			}

			::v-deep .u-textarea {
				margin-top: 25upx;
				display: flex;
				justify-content: space-between;
				padding: 0;
				// height: 60upx;
				font-size:30upx;
			}

			::v-deep .u-textarea__count {
				position: relative;
			}
		}

		.describe-title{

			::v-deep .u-textarea {
				margin-top: 25upx;
				// display: flex;
				display: block;
				// justify-content: space-between;
				padding: 0;
				// height: 60upx;
				font-size:30upx;
			}
			::v-deep .u-textarea__count {
				position: relative;
				display: block;
				text-align: right;
				margin-top: 10upx;
			}
		}
		.active-info {
			border-bottom: 1upx solid #EEEEEE;
			// padding: 37upx 0;
			.active-img-des{
				font-size: 24upx;
				color: rgb(153, 153, 153);
				margin-top: 20upx;
			}
			.active-info-img {
				margin: 0 auto;
				// margin-top: 30upx;
				// width: 690upx;
				// height: 350upx;
				border-radius: 30upx;
				position: relative;
				overflow: hidden;
				margin-top: 20upx;

				// border-bottom: 1upx solid #EEEEEE;
				// img {
				// 	width: 690upx;
				// 	height: 350upx;
				// }

				.active-info-mask {
					position: absolute;
					width: 690upx;
					height: 70upx;
					bottom: 0;
					background: linear-gradient(0deg, #000000 0%, rgba(0, 0, 0, 0.1000) 100%);
					line-height: 70upx;
					font-size: 24upx;
					font-family: PingFang SC;
					font-weight: 400;
					color: #FFFFFF;
					text-align: center;
				}
			}
		}


		.sign-up {
			margin-top: 120upx;
		}

		::v-deep .u-upload__deletable {
			right: 20upx;
			top: 20upx;
			width: 20upx;
			height: 20upx;
			text-align: center;
			border-bottom-left-radius: 0;

			// background: transparent;
			.u-icon--right {
				text {
					font-size: 30upx !important;
					top: 7upx !important;
					left: 6upx !important;
				}
			}
		}
	}
</style>
